package com.t.e.leaksdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class InnerClassLeaksActivity extends AppCompatActivity {

    private ArrayList<String> list = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inner_class_leaks);
        //模拟Activity一些其他的对象
        for (int i = 0; i < 10000; i++) {
            list.add("Memory Leak!");
        }
        //开启线程
//        new InnerClassHasLeak().start();
        new StaticInnerClassNoLeak(this).start();
    }

    public  class InnerClassHasLeak extends Thread{

        @Override
        public void run() {
            super.run();
            //模拟耗时操作
            try {
                Thread.sleep(10 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static class StaticInnerClassNoLeak extends Thread{
        private WeakReference<InnerClassLeaksActivity> mLeakActivityRef;

        public StaticInnerClassNoLeak(InnerClassLeaksActivity activity){
            mLeakActivityRef = new WeakReference<InnerClassLeaksActivity>(activity);
        }
        @Override
        public void run() {
            super.run();
            //模拟耗时操作
            try {
                Thread.sleep(10 * 60 * 1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //如果需要使用LeakActivity，我们需要添加一个判断
            InnerClassLeaksActivity activity = mLeakActivityRef.get();
            if(activity != null){
                //do something
            }
        }
    }



}
